package com.platform.rbac.example.exception;

import com.alibaba.fastjson.JSONObject;
import com.platform.rbac.exception.PermissionFailException;
import com.platform.rbac.exception.RoleFailException;
import com.platform.rbac.exception.TokenAutheFailException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 统一异常处理
 */
public class GlobalExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest,
                                         HttpServletResponse httpServletResponse, Object o,
                                         Exception e) {
        JSONObject data = new JSONObject();
        //token验证失败
        if (e instanceof TokenAutheFailException) {
            data.put("code", 401);
            data.put("msg", e.getMessage());
        } else if (e instanceof RoleFailException) {
            //角色验证失败
            data.put("code", 402);
            data.put("msg", e.getMessage());
        } else if (e instanceof PermissionFailException) {
            //权限验证失败
            data.put("code", 402);
            data.put("msg", e.getMessage());
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            data.put("code", 402);
            data.put("msg", e.getMessage());
        } else {
            data.put("code", 500);
            data.put("msg", "系统异常");
            e.printStackTrace();
        }


        responseResult(httpServletResponse, data.toJSONString());

        return new ModelAndView();
    }

    private void responseResult(HttpServletResponse response, String result) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setStatus(200);
        try {
            response.getWriter().write(result);
        } catch (IOException ex) {
//            logger.error(ex.getMessage());
        }
    }
}
